import React, { FC, useState, DragEvent } from 'react'
import {
  DraggerProps,
  DISPLAY_NAME_DRAGGER,
  getDraggerClassNames,
} from './config'

export const Dragger: FC<DraggerProps> = props => {
  const { onFile, children } = props

  const [dragOver, setDragOver] = useState(false)

  const draggerClasses = getDraggerClassNames(props, () => {
    return { 'is-dragover': dragOver }
  })

  const handleDrop = (e: DragEvent<HTMLElement>) => {
    e.preventDefault()
    setDragOver(false)
    onFile(e.dataTransfer.files)
  }
  const handleDrag = (e: DragEvent<HTMLElement>, over: boolean) => {
    e.preventDefault()
    setDragOver(over)
  }

  return (
    <div
      className={draggerClasses}
      onDragOver={e => {
        handleDrag(e, true)
      }}
      onDragLeave={e => {
        handleDrag(e, false)
      }}
      onDrop={handleDrop}>
      {children}
    </div>
  )
}
Dragger.displayName = DISPLAY_NAME_DRAGGER

export default Dragger
